package spring.exception;

import javax.servlet.http.HttpServletRequest ;

import org.json.JSONException ;
import org.json.JSONObject ;
import org.springframework.web.bind.annotation.ControllerAdvice ;
import org.springframework.web.bind.annotation.ExceptionHandler ;
import org.springframework.web.bind.annotation.ResponseBody ;
import org.springframework.web.servlet.ModelAndView ;

/**
 * 基于@ControllerAdvice注解，配合@ExceptionHandler异常实现全局异常处理
 * @author 80002165 @date 2017年6月15日 上午9:27:45
 */
@ControllerAdvice
public class SpringExceptionHandler {
    
    @ExceptionHandler({NullPointerException.class})
    public ModelAndView nullPointerExceptionHandler(NullPointerException ex){
        ModelAndView mv = new ModelAndView() ;
        mv.addObject("msg", String.format("系统抛出空指针异常：%s", ex.getMessage())) ;
        mv.setViewName("exception/err/error.html");
        return mv ;
    }
    
    @ExceptionHandler(RuntimeException.class)
    public String runtimeExceptionHandler(RuntimeException ex, HttpServletRequest request){
        request.setAttribute("msg", String.format("系统抛出异常：%s", ex.getMessage()));
        return "exception/err/error.html" ;
    }
    
    @ExceptionHandler(ArrayIndexOutOfBoundsException.class)
    @ResponseBody
    public String outOfBoundsExceptionHandler(ArrayIndexOutOfBoundsException ex){
        JSONObject json = new JSONObject() ;
        
        try {
            json.put("code", "101") ;
            json.put("msg", ex.getMessage()) ;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return json.toString() ;
    }
}
